package com.example.element.module.jetpack.workmanager

import android.content.Context
import android.content.Intent
import androidx.work.BackoffPolicy
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import com.example.common.base.AbsActivity
import com.example.element.R
import com.example.element.databinding.ActJetpackWorkerBinding
import java.util.concurrent.TimeUnit

class WorkerActivity : AbsActivity<ActJetpackWorkerBinding>() {

    companion object {
        @JvmStatic
        fun open(context: Context) {
            context.startActivity(Intent(context, WorkerActivity::class.java))
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.act_jetpack_worker
    }

    override fun main() {
//        WorkManager.getInstance(this).cancelAllWorkByTag("simple")    通过标签取消任务请求，可取消多个相同标签的任务
//        WorkManager.getInstance(this).cancelWorkById(request.id)      通过id取消任务请求
//        WorkManager.getInstance(this).cancelAllWork()         取消所有的后台任务请求

    }

    override fun initListener() {
        /**
         * 延时任务
         */
        mBinding.btnDoWork.setOnClickListener {
            val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java)
                    .setInitialDelay(5,TimeUnit.SECONDS)
                    .addTag("simple")
                    .build()
            WorkManager.getInstance(mContext).enqueue(request)
        }

        /**
         * 失败重复任务
         */
        mBinding.btnRepetitionDoWork.setOnClickListener {
            val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java)
                    .setInitialDelay(5,TimeUnit.SECONDS)
                    .setBackoffCriteria(BackoffPolicy.LINEAR,10,TimeUnit.SECONDS)       //第一个参数:下次重试的时间应该以什么样的形式延迟,第二个和第三个参数用于指定在多久之后重新执行任务，时间最短不能少于10秒钟;LINEAR和EXPONENTIAL，前者代表下次重试时间以线性的方式延迟，后者代表下次重试时间以指数的方式延迟。
                    .addTag("simple")
                    .build()
            WorkManager.getInstance(mContext).enqueue(request)
        }

        //通知结果
//        WorkManager.getInstance(this)
//                .getWorkInfoByIdLiveData(request.id)
//                .observe(this) { workInfo ->
//                    if (workInfo.state == WorkInfo.State.SUCCEEDED) {
//                        Log.d("MainActivity", "do work succeeded")
//                    } else if (workInfo.state == WorkInfo.State.FAILED) {
//                        Log.d("MainActivity", "do work failed")
//                    }
//                }

//链式任务：同步数据、压缩数据和上传数据。现在我们想要实现先同步、再压缩、最后上传的功能
//        val sync = ...
//        val compress = ...
//        val upload = ...
//        WorkManager.getInstance(this)
//                .beginWith(sync)
//                .then(compress)
//                .then(upload)
//                .enqueue()
    }
}